<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mdiscount extends Model {

    function Mdiscount() {
        parent::Model();
    }

    function new_discount($data){
        return $this->db->insert('discount',$data);
    }

    function get_member_discount($username) {
        $utype = substr(strtoupper($username),0,2);
        $sql = "SELECT SUM(D.discount) AS total FROM ".$this->db->dbprefix."discount AS D, ".$this->db->dbprefix."orders AS O WHERE D.order_id=O.order_id AND D.username='$username' ";
        if($utype == 'WB'){
            $sql .= " AND O.dai_state = 8";
        } elseif($utype == 'CM' || $utype == 'NB') {
            $sql .= " AND O.order_state = 5";
        }
        //AND O.order_state>=$state ";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row['total'];
    }

    function get_member_order_count($username) {
        $utype = substr(strtoupper($username),0,2);
        $sql = "SELECT COUNT(*) AS total FROM ".$this->db->dbprefix."orders WHERE (uid='$username' OR dai='$username') ";
        if($utype == 'WB'){
            $sql .= " AND dai_state = 8";
        } elseif($utype == 'CM' || $utype == 'NB') {
            $sql .= " AND order_state = 5";
        }
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row['total'];
    }

    function get_member_order_price($username) {
        $utype = substr(strtoupper($username),0,2);
        $sql = "SELECT SUM(D.price) AS total FROM ".$this->db->dbprefix."discount AS D, ".$this->db->dbprefix."orders AS O WHERE D.order_id=O.order_id AND D.username='$username' ";
        if($utype == 'WB'){
            $sql .= " AND O.dai_state = 8";
        } elseif($utype == 'CM' || $utype == 'NB') {
            $sql .= " AND O.order_state = 5";
        }
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row['total'];
    }

    function delete_discount($orderid,$username){
    	return $this->db->delete('discount',array('order_id'=>$orderid,'username'=>$username));
    }

}

?>
